<template>
	<view class="container" @tap="togglePicker(0)">
		<!--内容-->
		<view class="scroll" :style="{ height: scrollHeight }">
			<scroll-view :scroll-into-view="scrollViewId" scroll-y style="height: 100%;">
				<view class="item-space"></view>
				<!-- <view class="time">晚上 10:04</view> -->
				<view v-for="(item, index) in list" :key="index">
					<!--撤销-->
					<view v-if="item.messageType == 'cancel'" class="cancel">
						<text v-if="item.messageDirection == 1" class="text">你撤回了一条消息</text>
						<text v-else class="text">成员 {{ item.senderUserId }} 撤回了一条消息</text>
					</view>
					<view v-else class="item flex-row" :class="[item.messageDirection == 1 ? 'right' : 'left']">
						<!--处理头像-->
						<view v-if="item.messageDirection == 1">
							<image :src="fromUserFace || '/static/img/face.png'" class="face"></image>
						</view>
						<view v-else>
							<image :src="toUserAvatar || '/static/img/face.png'" class="face"></image>
						</view>
						<!--文本-->
						<view v-if="item.messageType == 'RC:TxtMsg'" @longpress="longPress(item)"
							class="content flex-row">{{ item.content.content }}</view>
						<!--图片-->
						<view v-if="item.messageType == 'RC:ImgMsg'" class="m-flex-y u-flex-items-end">
							<image @longpress="longPress(item)" :src="item.content.imageUri" mode="widthFix"
								style="width: 320rpx;"></image>
							<view class="extra" v-if="item.content.extra">{{ item.content.extra }}</view>
						</view>
						<!--地图-->
						<view v-if="item.messageType == 'RC:LBSMsg'" class="content map"
							@tap="openLocation(item.content.latitude, item.content.longitude)">
							<view class="title">{{ item.content.poi }}</view>
							<map class="box" :latitude="item.content.latitude" :longitude="item.content.longitude"
								:markers="[{ alpha: 0.9, width: 20, height: 25, latitude: item.content.latitude, longitude: item.content.longitude, iconPath: '/static/map/2.png' }]"
								@tap="openLocation(item.content.latitude, item.content.longitude)"></map>
						</view>
						<!--语音-->
						<view v-if="item.messageType == 'RC:HQVCMsg'" @tap="playVoice(item)" class="content">
							<image v-show="voicePlayingId != item.id" src="/static/img/audio.png" class="voice-icon">
							</image>
							<image v-show="voicePlayingId == item.id" src="/static/img/audio-play.gif"
								class="voice-icon"></image>
						</view>
					</view>
				</view>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<!--输入-->
		<view class="oper" :style="{ height: 55 + sys.bottom + 'px', paddingBottom: sys.bottom + 'px' }"
			@tap.prevent.stop="">
			<view class="flex-row u-m-t-20">
				<!--语音切换-->
				<image src="/static/img/voice-circle.png" class="icon"></image>
				<!-- <image v-if="isEdit" @tap="toggleEdit(false)" src="/static/img/voice-circle.png" class="icon"></image>
			<image v-else @tap="toggleEdit(true)" src="/static/img/keyboard.png" class="icon"></image> -->
				<!--语音切换-->
				<input v-if="isEdit" @focus="inputFocus" :focus="isFocus" :cursor-spacing="8" :adjust-position="false"
					type="text" v-model="content" class="input" placeholder="请输入内容" />
				<view v-else @touchstart="startVoice" @touchend="endVoice" class="input" style="text-align: center;">
					按住开吼</view>
				<!--表情-->
				<image @tap="togglePicker(200, 'emoji')" src="/static/img/emoji.png" class="icon"></image>
				<!--发送-->
				<view @touchend.prevent="send" v-show="content" class="btn">发送</view>
				<!--附件-->
				<image @tap="togglePicker(86, 'file')" v-show="!content" src="/static/img/add.png" class="icon"></image>
			</view>
			<!--表情-->
			<view v-show="showEmoji" class="emoji" @tap.prevent.stop="">
				<view class="list">
					<view class="item" @tap="content += item" v-for="(item, index) in emojis" :key="index">{{ item }}
					</view>
				</view>
			</view>
			<!--附件-->
			<view v-show="showFile" class="file" @tap.prevent.stop="">
				<view class="list flex-row">
					<view class="item flex-column" @tap="uploadImage(['album'])">
						<image src="/static/img/album.png" mode="widthFix" class="icon"></image>
						<view class="text">相册</view>
					</view>
					<view class="item flex-column" @tap="uploadImage(['camera'])">
						<image src="/static/img/photo.png" mode="widthFix" class="icon"></image>
						<view class="text">拍照</view>
					</view>
					<view class="item flex-column" @tap="getLocation">
						<image src="/static/img/location.png" mode="widthFix" class="icon"></image>
						<view class="text">位置</view>
					</view>
				</view>
			</view>
		</view>
		<!--语音-->
		<my-voice v-show="showVoice"></my-voice>
		<w-compress ref="wCompress" />
	</view>
</template>

<script>
	import uploadImageFile from '@/js_sdk/yushijie-ossutil/ossutil/uploadFile.js';
	import emoji from '@/common/emoji.js';

	const innerAudioContext = uni.createInnerAudioContext();
	const recorderManager = uni.getRecorderManager();
	export default {
		data() {
			return {
				emojis: [],
				isEdit: true,
				isFocus: false,
				showEmoji: false,
				showFile: false,
				showVoice: false,
				scrollHeight: 'auto', // 内容区域高度
				statusBarHeight: 0, // 状态栏高度
				scrollViewId: '', // 滚动到最底部
				voicePlayingId: '', // 正在播放的消息ID
				content: '',
				list: [],
				socketOpen: false,
				socketMsgQueue: [],
				fromUserId: uni.getStorageSync('senderUserId'),
				fromUserFace: JSON.parse(uni.getStorageSync('userInfo')).avatar,
				toUserName: '',
				toUserAvatar: '',
				rongUserId: ''
			};
		},
		async onLoad(e) {
			// #ifdef MP-WEIXIN
			uni.hideShareMenu();
			// #endif
			if (!e.id) {
				this.$u.toast('数据异常,即将返回');
				return setTimeout(() => {
					this.nextNav('back');
				}, 1000);
			}
			// 初始化内容高度
			this.setScrollHeight();

			// 初始化状态栏高度
			uni.getSystemInfo({
				success: res => {
					this.statusBarHeight = res.statusBarHeight;
				}
			});

			// 结束录音
			recorderManager.onStop(res => {
				this.upload(res.tempFilePath);
			});

			// 结束播放
			innerAudioContext.onEnded(res => {
				this.voicePlayingId = '';
			});

			// 设置标题
			let taInfo = await this.require('getiduser', {
				id: e.id
			});
			if (taInfo && taInfo.senderUserId) {
				uni.setNavigationBarTitle({
					title: taInfo.name || taInfo.nickname
				});
				this.toUserName = taInfo.name || taInfo.nickname;
				this.toUserAvatar = taInfo.avatar;
				this.rongUserId = taInfo.senderUserId;
			} else {
				return this.$u.toast('用户信息错误');
			}
			// 获取参数
			this.emojis = emoji;
			let that = this;
			// 获取消息记录
			await this.getnewList();
			// 监听消息通知
			this.$ry.watch({
				message(event) {
					// 新接收到的消息内容
					const message = event.message;
					// 只接受单聊消息
					if (message.type != 1) return;
					that.list.push(message);
					that.initScrollBar();
				}
			});
			let conversation = this.$ry.Conversation.get({
				targetId: this.rongUserId,
				type: 1
			});
			conversation.read().then(function() {
				console.log('清除未读数成功');
			});
		},
		onHide() {
			innerAudioContext.stop();
		},
		onUnload() {
			let conversation = this.$ry.Conversation.get({
				targetId: this.rongUserId,
				type: 1
			});
			conversation.read().then(function() {
				console.log('清除未读数成功');
			});
			if (this.showFile || this.showEmoji) {
				this.showFile = false;
				this.showEmoji = false;
				this.setScrollHeight(0);
				return true;
			}
			return false;
		},
		methods: {
			// 初始化滚动
			initScrollBar() {
				setTimeout(() => {
					this.scrollViewId = '';
					setTimeout(() => {
						this.scrollViewId = 'bottom';
						setTimeout(() => {
							this.scrollViewId = '';
						}, 100);
					}, 100);
				}, 100);
			},
			// 监听输入聚焦
			inputFocus(e) {
				this.setScrollHeight(e.detail.height);
				this.initScrollBar();

				uni.onKeyboardHeightChange(res => {
					this.setScrollHeight(res.height);
					this.initScrollBar();
				});
			},
			// 设置scroll的高度
			setScrollHeight(descHeight = 0) {
				// #ifdef MP-WEIXIN
				this.scrollHeight = `calc(100vh - 110rpx - ${descHeight}px)`;
				// #endif
				// #ifdef APP-PLUS
				this.scrollHeight = `calc(100vh - 110upx - ${descHeight}px)`;
				// #endif
				// #ifdef H5
				this.scrollHeight = `calc(100vh - 110upx - 88rpx - ${descHeight}px)`;
				// #endif
			},
			// 切换选择
			togglePicker(height = 0, type = '') {
				this.showEmoji = false;
				this.showFile = false;
				let status = height > 0 ? true : false;

				switch (type) {
					case 'emoji':
						this.showEmoji = status;
						break;
					case 'file':
						this.showFile = status;
						break;
				}

				setTimeout(() => {
					this.setScrollHeight(height);
					this.initScrollBar();
				}, 50);
			},
			// 切换语音与编辑
			toggleEdit(bool) {
				this.isEdit = bool;
				this.isFocus = bool;
				this.setScrollHeight(0);
			},
			// 开始录音
			startVoice() {
				this.showVoice = true;
				recorderManager.start();
			},
			// 结束录音
			endVoice() {
				this.showVoice = false;
				recorderManager.stop();
			},
			// 上传

			upload(filePath) {
				uni.showLoading({
					title: '上传中'
				});
				uploadImageFile(
					filePath,
					'news/' + uni.$u.timeFormat(new Date(), 'yyyymmdd'),
					remoteUrl => {
						uni.hideLoading();
						this.pushMessage({
								remoteUrl
							},
							'RC:HQVCMsg'
						);
					},
					result => {
						//这里写上传失败的代码
						console.log(JSON.stringify(result));
					}
				);
			},
			// 播放录音
			playVoice(item) {
				if (this.voicePlayingId) {
					this.voicePlayingId = '';
				} else {
					this.voicePlayingId = item.id;
					innerAudioContext.src = item.content;
					innerAudioContext.play();
				}
			},
			// 长按
			longPress(msg) {
				console.log(msg);
			},
			// 获取位置
			getLocation() {
				uni.getLocation({
					success: res => {
						let {
							latitude,
							longitude
						} = res;
						uni.chooseLocation({
							latitude,
							longitude,
							success: chooseRes => {
								console.log(chooseRes);
								this.pushMessage({
									latitude: chooseRes.latitude,
									longitude: chooseRes.longitude,
									poi: chooseRes.address,
									content: '地图'
								}, 'RC:LBSMsg');
							}
						});
					}
				});
			},
			// 打开位置
			openLocation(latitude, longitude) {
				uni.openLocation({
					latitude,
					longitude
				});
			},
			/* 图片压缩 */
			async imgcompress(tempFilePaths, type) {
				let res = await this.$refs.wCompress
					.start(tempFilePaths, {
						pixels: 500000, // 最大分辨率，默认二百万
						quality: 0.5, // 压缩质量，默认0.8
						type, // 图片类型，默认jpg
						base64: true // 是否返回base64，默认false，非H5有效
					})
					.catch(err => {
						return err;
					});
				return res;
			},
			// 发送图片
			uploadImage(sourceType = ['album']) {
				let that = this;
				uni.chooseImage({
					sourceType,
					sizeType: ['compressed'],
					success: chooseImageRes => {
						const tempFilePaths = chooseImageRes.tempFilePaths;

						tempFilePaths.forEach(async temp => {
							uni.showLoading({
								title: '上传中'
							});
							let type = temp.split('/')[1];
							let e = await this.imgcompress(temp, type);
							let base64 = e ? e.url : 'base';
							uploadImageFile(
								temp,
								'news/' + uni.$u.timeFormat(new Date(), 'yyyymmdd'),
								result => {
									console.log(result);
									uni.hideLoading();
									this.pushMessage({
											content: base64,
											imageUri: result
										},
										'RC:ImgMsg'
									);
								},
								result => {
									//这里写上传失败的代码
									console.log(JSON.stringify(result));
								}
							);
						});
					}
				});
			},
			// 发送消息
			send() {
				this.pushMessage({
					content: this.content
				}, 'RC:TxtMsg', () => {
					this.content = '';
				});
			},
			// 推送消息
			pushMessage(content, messageType = 'RC:TxtMsg', cb = () => {}) {
				let that = this,
					conversation = that.$ry.Conversation.get({
						targetId: that.rongUserId,
						type: 1
					});
				conversation.send({
					messageType,
					content
				}).then(message => {
					console.log(message);
					// that.$u.toast('发送成功！');
					// 加入信息
					that.list.push(message);
					// 初始化滚动条
					that.initScrollBar();
					cb ? cb() : that.togglePicker(0, 'file');
				});
			},
			// 获取记录
			async getnewList() {
				let that = this,
					conversation = that.$ry.Conversation.get({
						targetId: that.rongUserId,
						type: 1
					}),
					option = {
						timestamp: +new Date(),
						count: 20
					};
				conversation.getMessages(option).then(result => {
					that.list = result.list;
					// if (!that.list.length) {
					// 	this.pushMessage(
					// 		{
					// 			content: 'base64',
					// 			imageUri: this.oss + '/df/hello.png',
					// 			extra: '【风险提醒】以免造成不必要损失，请客官依据平台规则进行交易，否则由个人承担相应后果，感谢您的支持！'
					// 		},
					// 		'RC:ImgMsg'
					// 	);
					// }
					this.scrollViewId = '';
					setTimeout(() => {
						this.scrollViewId = 'bottom';
						setTimeout(() => {
							this.scrollViewId = '';
						}, 100);
					}, 100);
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import url('@/css/base.css');

	.container {
		height: 100vh;
		overflow: hidden;
	}

	/* #ifdef H5 */
	.container {
		height: calc(100vh - 88upx);
	}

	/* #endif */

	.status_bar,
	.container,
	.header,
	.emoji,
	.file {
		background-color: #f3f3f3;
	}

	.header {
		border-bottom: 2upx solid #eee;

		.center {
			font-weight: bold;
		}
	}

	.map {
		width: 60%;
		height: 300rpx;
		background-color: #fff !important;

		&::before {
			border-right: 30upx solid #fff !important;
		}

		.title {
			height: 80rpx;
			font-size: 28rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
		}

		.box {
			width: 100%;
			height: 170rpx;
			margin-top: 10rpx;
		}
	}

	.emoji {
		height: 400rpx;
		padding: 0 0 20upx 20rpx;
		position: relative;

		.list {
			width: 100%;
			height: 400rpx;
			padding: 20upx 0;
			overflow-y: auto;

			.item {
				float: left;
				display: block;
				height: 60rpx;
				line-height: 60rpx;
				width: calc(100% / 12);
				margin-right: 20rpx;
			}
		}
	}

	.file {
		padding: 30upx 20rpx;

		.list {
			overflow: hidden;
			padding-left: 10rpx;
			justify-content: flex-start;
		}

		.item {
			float: left;
			width: 110rpx;
			height: 110rpx;
			border-radius: 10rpx;
			margin-right: 40rpx;
			background-color: #fff;

			.icon {
				width: 50rpx;
			}

			.text {
				font-size: 24rpx;
				margin-top: 4rpx;
			}
		}
	}

	.oper {
		height: 110rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		border-top: 2upx solid #eee;
		border-bottom: 2upx solid #eee;

		.input {
			height: 68rpx;
			line-height: 68rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			border-radius: 10rpx;
			background-color: #fff;
			width: calc(100% - 120upx - 20upx - 40upx - 60upx);
		}

		.icon {
			width: 60rpx;
			height: 60rpx;
		}

		.btn {
			color: #fff;
			width: 90rpx;
			height: 52rpx;
			font-size: 24rpx;
			line-height: 52rpx;
			text-align: center;
			border-radius: 10rpx;
			background-color: #2ba245;
		}
	}

	.scroll {
		overflow-y: auto;
		transition: all 0.1s ease;
		height: calc(100vh - 88upx - 110upx - var(--status-bar-height));

		/* #ifdef MP-WEIXIN */
		height: calc(100vh - 88upx - var(--status-bar-height));
		/* #endif */
		/* #ifdef H5 */
		height: calc(100vh - 88upx - 110upx - var(--status-bar-height));
		/* #endif */

		.item-space {
			height: 30rpx;
		}

		.time {
			color: #666;
			font-size: 24rpx;
			text-align: center;
			margin-bottom: 20rpx;
		}

		.cancel {
			width: 100%;
			height: 40rpx;
			text-align: center;
			margin-bottom: 30rpx;

			.text {
				color: #999;
				font-size: 24rpx;
			}
		}

		.item {
			margin: 0 30upx 30rpx;
			align-items: flex-start;
			justify-content: flex-start;

			.face {
				width: 80rpx;
				height: 80rpx;
				border-radius: 10rpx;
			}

			.content {
				color: #000;
				font-size: 32rpx;
				min-height: 80rpx;
				border-radius: 10rpx;
				padding: 20upx 24rpx;
				background-color: #fff;
				word-break: break-all;
				word-wrap: break-word;
				max-width: calc(100% - 100upx - 120upx);
				position: relative;

				&::before {
					content: '';
					width: 0;
					height: 0;
					border-right: 30upx solid #fff;
					border-top: 20upx solid transparent;
					border-bottom: 20upx solid transparent;
					position: absolute;
					top: 24rpx;
				}

				.voice-icon {
					width: 32rpx;
					height: 40rpx;
					margin-right: 180rpx;
					margin-bottom: -8rpx;
				}
			}

			&.left {
				.face {
					margin-right: 30rpx;
				}

				.content::before {
					left: -20rpx;
				}
			}

			&.right {
				flex-direction: row-reverse;

				.face {
					margin-left: 30rpx;
				}

				.content {
					background-color: #a0ea6f;

					&::before {
						right: -20rpx;
						transform: rotate(180deg);
						border-right: 30upx solid #a0ea6f;
					}

					.voice-icon {
						margin-right: 0;
						margin-left: 180rpx;
						transform: rotate(180deg);
					}
				}
			}
		}

		#bottom {
			height: 0;
		}

		.extra {
			padding: 8rpx 22rpx;
			color: #f6f6f6;
			background: #d5d5d5;
			border-radius: 6rpx;
			margin-top: 10rpx;
			font-size: 20rpx;
		}
	}
</style>
